<template>
  <div class="app-container">
    <el-form ref="queryForm" :model="queryParams" size="mini" inline>
      <el-form-item prop="deptId1">
        <treeselect
          v-model="queryParams.deptId1"
          class="tree-select-custom"
          :options="deptOptions"
          no-results-text="暂无数据匹配"
          no-options-text="暂无数据"
          :normalizer="normalizerDept"
          @select="getProjectList"
          placeholder="请选择所属部门"
        />
      </el-form-item>
      <el-form-item prop="projectName">
        <el-input v-model.trim="queryParams.projectName" placeholder="请输入项目名称" clearable @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item prop="rdcType">
        <el-select v-model="queryParams.rdcType" placeholder="检查单位" clearable style="width: 100px">
          <el-option v-for="dict in dict.type.cq_eval_rdc_type" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item prop="isLockout">
        <el-select v-model="queryParams.isLockout" placeholder="锁定状态" clearable style="width: 100px">
          <el-option v-for="dict in lockStatusList" :key="dict.value" :label="dict.label" :value="dict.value" />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-date-picker
          v-model="dateRange"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="检查开始日期"
          end-placeholder="检查结束日期"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" @click="resetQuery">重置</el-button>
        <el-button type="primary" icon="el-icon-plus" v-if="showBtns.add" @click="handleAdd(CQ_EVAL_RDC_TYPE.DEPT2)">新增</el-button>
        <el-button icon="el-icon-download" :loading="exportLoading" @click="handleExport" v-if="showBtns.isExport">导出</el-button>
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" size="small" ref="projectScoreTableRef" :data="list" height="calc(100vh - 200px)">
      <el-table-column label="所属部门" prop="showDeptName" align="center" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="项目" prop="projectName" align="center" :show-overflow-tooltip="true" width="150" />
      <el-table-column label="项目(检查口径)" prop="inpectionCaliber" align="center" :show-overflow-tooltip="true" width="120" />
      <el-table-column label="施工单位" prop="constructionName" align="center" :show-overflow-tooltip="true" width="100" />
      <el-table-column label="批次" prop="phaseName" align="center" :show-overflow-tooltip="true" width="100" />
      <el-table-column label="检查单位" align="center" min-width="80">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_eval_rdc_type" :value="row.rdcType" />
      </el-table-column>
      <el-table-column label="交付类型" align="center" min-width="100">
        <dict-tag slot-scope="{ row }" :options="dict.type.cq_eval_delivery_type" :value="row.deliveryTypes" />
      </el-table-column>
      <el-table-column v-for="item in checkItemList" :key="item.chkitemId" :label="item.chkitemName" align="center" min-width="70">
        <!--<template v-if="shareItemCode.some(code => code === item.chkitemCode)" slot-scope="{ row }">-->
        <!--<span class="default-level" :class="row | scoreClass(item.chkitemCode, deliveryType.JZMP)">{{ row | scoreName(item.chkitemCode, deliveryType.JZMP, dict.type.cq_eval_result_enum) }}</span>-->
        <!--</template>-->
        <!--<el-table-column v-if="!shareItemCode.some(code => code === item.chkitemCode)" label="精装" align="center" min-width="60">-->
        <!--<template slot-scope="{ row }">-->
        <!--<span class="default-level" :class="row | scoreClass(item.chkitemCode, deliveryType.JZ)">{{ row | scoreName(item.chkitemCode, deliveryType.JZ, dict.type.cq_eval_result_enum) }}</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <!--<el-table-column v-if="!shareItemCode.some(code => code === item.chkitemCode)" label="毛坯" align="center" min-width="60">-->
        <!--<template slot-scope="{ row }">-->
        <!--<span class="default-level" :class="row | scoreClass(item.chkitemCode, deliveryType.MP)">{{ row | scoreName(item.chkitemCode, deliveryType.MP, dict.type.cq_eval_result_enum) }}</span>-->
        <!--</template>-->
        <!--</el-table-column>-->
        <el-table-column label="精装" align="center" min-width="60">-->
          <template slot-scope="{ row }">
            <span class="default-level" :class="row | scoreClass(item.chkitemCode, deliveryType.JZ)">{{ row | scoreName(item.chkitemCode, deliveryType.JZ, dict.type.cq_eval_result_enum) }}</span>
          </template>
        </el-table-column>
        <el-table-column label="毛坯" align="center" min-width="60">
          <template slot-scope="{ row }">
            <span class="default-level" :class="row | scoreClass(item.chkitemCode, deliveryType.MP)">{{ row | scoreName(item.chkitemCode, deliveryType.MP, dict.type.cq_eval_result_enum) }}</span>
          </template>
        </el-table-column>
      </el-table-column>
      <el-table-column label="锁定状态" align="center" width="70" fixed="right">
        <div slot-scope="{ row }">
          <div @click="toggleLock(row)" style="display: inline-block; cursor: pointer" v-if="row.isEditLock">
            <i class="el-icon-loading" v-if="!!row.lockLoading" />
            <el-switch class="g-switch-in" v-model="row.isLockout" :active-value="1" :inactive-value="0" active-text="锁定" inactive-text="未锁" :width="50" style="pointer-events: none" v-else />
          </div>
          <el-tag size="small" :type="row.isLockout ? 'primary' : 'info'" v-else>{{ row.isLockout ? '锁定' : '未锁' }}</el-tag>
        </div>
      </el-table-column>
      <el-table-column label="检查日期" align="center" prop="checkDate" min-width="100" />
      <el-table-column label="操作" width="160" fixed="right" class-name="small-padding">
        <template slot-scope="{ row }">
          <el-button size="mini" v-if="row.rdcType==CQ_EVAL_RDC_TYPE.DEPT2 && showBtns.add" type="text" icon="el-icon-edit" @click="handleAdd(CQ_EVAL_RDC_TYPE.DEPT1, row)">集团检查</el-button>
          <el-button size="mini" v-if="showBtns.edit && !row.isLockout" type="text" icon="el-icon-edit" @click="handleUpdate(row)">修改</el-button>
          <el-button size="mini" v-if="showBtns.remove && !row.isLockout" type="text" icon="el-icon-delete" @click="handleDelete(row)">删除</el-button>
          <el-button size="mini" type="text" icon="el-icon-tickets" @click="openDetail(row)" v-if="showBtns.info">详情</el-button>
          <el-button size="mini" type="text" icon="el-icon-edit" @click="openProblemInput(row)" v-if="showBtns.problemInput && !row.isLockout">问题录入</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

    <EditProjectScore ref="editProjectScoreRef" :cfg="cfgInfo" @ok="getList" />

    <EvalProblemDialog ref="EvalProblemDialog" />

    <ChkitemScoreDetail ref="ChkitemScoreDetail" :show-scores="false">
      <template v-slot:default="{ info }">
        <DeliveryScoreDisplay :value="info" :cfg="cfgInfo" />
        <div v-if="info.sysFiles">
          <div style="width: 110px"><el-divider content-position="left">文件</el-divider></div>
          <SysFilesDisplay :file-list="info.sysFiles" />
        </div>
      </template>
    </ChkitemScoreDetail>
  </div>
</template>
<script>
import { CQ_EVAL_DATA_TYPE as DATA_TYPE } from '@/utils/baseData'
import {
  cqEvalPrjchkPage, exsitJtchk
} from '@/api/checkScore/projectScore'
import { listChkitem, deletePrjchk, enableTaskPrjchk, disableTaskPrjchk, exportReportPrjchk } from '@/api/checkScore/cqEval'
import EditProjectScore from './EditProjectScore'
import { treeselect } from '@/api/system/dept'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { shareItemCode, deliveryType, CQ_EVAL_RDC_TYPE, CQ_EVAL_RESULT_ENUM as RESULT, lockStatusList } from '@/utils/baseData'
import { selectProjectExcludeCfProjectStage } from '@/api/baseManage/project'
import auth from '@/plugins/auth'
import EvalProblemDialog from '@/views/checkScore/components/evalProblem/EvalProblemDialog'
import ChkitemScoreDetail from '@/views/checkScore/chkitemScore/ChkitemScoreDetail'
import DeliveryScoreDisplay from './DeliveryScoreDisplay'
import SysFilesDisplay from './SysFilesDisplay'
export default {
  name: 'VersionDefault',
  components: { EditProjectScore, Treeselect, EvalProblemDialog, ChkitemScoreDetail, DeliveryScoreDisplay, SysFilesDisplay },
  dicts: ['cq_eval_rdc_type', 'cq_process_type', 'cq_eval_delivery_type', 'cq_eval_abc', 'cq_eval_result', 'cq_eval_result_enum', 'cq_eval_valid'],
  filters: {
    scoreClass(item = {}, chkitemCode, deliveryType) {
      let val = ''
      if (item && item.scores) {
        for (let i = 0; i < item.scores.length; i++) {
          if (item.scores[i].chkitemCode === chkitemCode && deliveryType.includes(item.scores[i].deliveryType)) {
            val = item.scores[i].scoreResult
          }
        }
      }
      if (val === RESULT.EXCELLENT) return 'green'
      if (val === RESULT.VALID) return 'blue'
      if (val === RESULT.UNVALID) return 'red'
      return ''
    },
    scoreName(item = {}, chkitemCode, deliveryType, dicts = []) {
      let val = '/'
      if (item && item.scores) {
        for (let i = 0; i < item.scores.length; i++) {
          if (item.scores[i].chkitemCode === chkitemCode && deliveryType.includes(item.scores[i].deliveryType)) {
            if (item.scores[i].scoreInput) {
              val = `${item.scores[i].scoreInput}`
              dicts.forEach(item => {
                if (val === item.value) {
                  val = item.label
                }
              })
            }
            // if (item.scores[i].scoreNum) {
            //   val += `(${item.scores[i].scoreNum})`
            // }
          }
        }
      }
      return val
    }
  },
  data() {
    return {
      deliveryType,
      CQ_EVAL_RDC_TYPE,
      lockStatusList,
      loading: false,
      formProjectOptions: [],
      total: 0,
      list: [],
      // 日期范围
      dateRange: [],
      // 部门树选项
      deptOptions: [],
      // 查询参数
      queryParams: {
        chkitemCode: '',
        versionCode: '',
        rdcType: '',
        isLockout: '',
        pageNum: 1,
        pageSize: 20,
        projectName: undefined,
        startTime: '',
        endTime: ''
      },
      queryCheckParams: {
        versionCode: '',
        parentId: '',
        isEnable: 1
      }, // 检查项参数
      showSearch: true,
      exportLoading: false,
      showEdit: false,
      specialTypes: [],
      query: {},
      checkItemList: [],
      cfgLoading: false,
      cfgInfo: {},
      shareItemCode: shareItemCode
    }
  },
  computed: {
    showBtns() {
      // 操作按钮权限
      const permCode = this.$route.query.permCode
      const edit = auth.hasPermi(`cq:eval:${permCode}:edit`)
      const add = auth.hasPermi(`cq:eval:${permCode}:add`)
      const remove = auth.hasPermi(`cq:eval:${permCode}:remove`)
      const info = auth.hasPermi(`cq:eval:${permCode}:info`)
      // 有权解锁(启用)
      const enable = auth.hasPermi(`cq:eval:${permCode}:enable`)
      // 有权锁定(禁用)
      const disable = auth.hasPermi(`cq:eval:${permCode}:disable`)
      const isExport = auth.hasPermi(`cq:eval:${permCode}:export`)
      const problemInput = auth.hasPermi(`cq:eval:${permCode}:problemInput`)
      return { edit, add, remove, info, enable, disable, isExport, problemInput }
    }
  },
  created() {
    this.query = this.$route.query
    this.queryCheckParams.parentId = this.query.chkitemId
    this.queryCheckParams.versionCode = this.query.versionCode
    this.queryParams.versionCode = this.query.versionCode
    this.queryParams.chkitemCode = this.query.chkitemCode
    this.getDeptTree()
    this.getCheckItemList()
    this.getAuthUserProjectList()
    console.log(this.query)
  },
  methods: {
    async toggleLock(item) {
      if (item.lockLoading) return
      const isLockout = item.isLockout ? 0 : 1
      const name = isLockout === 1 ? '锁定' : '解锁'
      const res1 = await this.$confirm(`确认${name}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      const opt = { prjchkId: item.prjchkId, isLockout }
      const submitApi = isLockout ? disableTaskPrjchk : enableTaskPrjchk
      item.lockLoading = true
      const res = await submitApi(opt).catch(() => false)
      item.lockLoading = false
      if (res === false) return

      this.$message.success(`已${name}`)
      this.getList()
    },
    // 获取授权的用户的项目列表
    async getAuthUserProjectList() {
      const res = await selectProjectExcludeCfProjectStage({ needUserId: false }).catch(() => false)
      if (res === false) return
      this.formProjectOptions = res.data || []
    },
    /** 查询检查列表 */
    async getCheckItemList() {
      const query = this.$route.query || {}
      this.cfgInfo = JSON.parse(JSON.stringify(query))

      this.cfgLoading = true
      const res = await listChkitem(this.queryCheckParams).catch(() => false)
      this.cfgLoading = false
      if (res === false) return

      const data = res.data || []
      await this.getEnumDicts(data)
      data.map(i => (i.chkitemCfgId = i.cfgId))
      // 排序
      data.sort((a, b) => {
        if (a.seq !== b.seq) return b.seq - a.seq
        return (a.chkitemCode || '').localeCompare(b.chkitemCode || '')
      })
      this.cfgInfo.children = JSON.parse(JSON.stringify(data))
      data[0].chkitemName = '承诺一致性'
      data[1].chkitemName = '产品舒适度'
      data[2].chkitemName = '客诉舆情'
      data[3].chkitemName = '建筑效果'
      data[4].chkitemName = '景观效果'
      data[5].chkitemName = '公区效果'
      data[6].chkitemName = '质量'
      data[7].chkitemName = '防渗漏'
      data[8].chkitemName = '工艺观感'
      data[9].chkitemName = '交付得分'
      this.checkItemList = data
      this.getList()
    },
    async getEnumDicts(list) {
      // 获取枚举字典
      const enumList = list.filter(i => i.dataType === DATA_TYPE.ENUM)
      if (!enumList.length) return list

      const arr = enumList.map(i => i.scoreType)
      // 去重
      const dictNames = arr.filter((a, b) => arr.indexOf(a) === b)

      this.cfgLoading = true
      const res = await Promise.all(
        dictNames.map(dictName =>
          this.getDicts(dictName)
            .then(res => ({ [dictName]: (res.data || []).map(i => ({ label: i.dictLabel, value: i.dictValue, raw: i })) }))
            .catch(() => ({}))
        )
      ).catch(() => false)
      this.cfgLoading = false
      if (res === false) return list

      const data = res.reduce((o, i) => !void (o = { ...o, ...i }) && o, {})
      enumList.map(i => (i.enumDicts = data[i.scoreType] || []))
      return list
    },
    /** 查询 交付列表 */
    async getList() {
      const { showBtns } = this
      const opt = this.getQuery()
      if (!opt) return

      this.loading = true
      const res = await cqEvalPrjchkPage(opt).catch(() => false)
      this.loading = false
      if (res === false) return

      const data = res.rows || []
      const deptName = i => [i.deptName1, i.deptName2, i.deptName3].filter(i => i).join(' - ')
      data.forEach(item => {
        item.showDeptName = deptName(item)
        item.removeLoading = false
        item.lockLoading = false
        item.isEditLock = item.isLockout ? showBtns.enable : showBtns.disable
      })
      this.list = data
      this.total = res.total || 0
      this.$nextTick(() => {
        this.$refs.projectScoreTableRef.doLayout()
      })
    },
    getQuery() {
      const { dateRange } = this
      const opt = { ...this.queryParams }
      if (Array.isArray(dateRange) && dateRange.length === 2) {
        opt.startTime = dateRange[0]
        opt.endTime = dateRange[1]
      } else {
        opt.startTime = ''
        opt.endTime = ''
      }
      return opt
    },
    /** 新增按钮操作 */
    async handleAdd(rdcType, relationObj) {
      const options = {checkItemList: this.checkItemList, formProjectOptions: this.formProjectOptions, rdcType: rdcType, relationObj: relationObj }
      if (rdcType === CQ_EVAL_RDC_TYPE.DEPT1) {
        this.loading = true
        // 判断集群是否已经有相应的 集团检查
        const res = await exsitJtchk({prjchkId: relationObj.prjchkId}).catch((e) => {
          console.log(e)
        }).finally(() => {
          this.loading = false
        })
        if (res && res.code === 200 && res.data && res.data.length > 0) {
          this.$confirm(`已存在相关集团检查，是否继续增加集团检查？`, '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            this.$refs.editProjectScoreRef.init(null, options)
          })
        } else {
          this.$refs.editProjectScoreRef.init(null, options)
        }
      } else {
        this.$refs.editProjectScoreRef.init(null, options)
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const options = {checkItemList: this.checkItemList, formProjectOptions: this.formProjectOptions }
      this.$refs.editProjectScoreRef.init(row, options)
    },
    /**
         * 查询部门与项目下拉树结构
         */
    getDeptTree() {
      treeselect({}).then((response) => {
        this.deptOptions = response.data
      })
    },
    getProjectList(node) {
      this.queryParams.projectName = ''
    },
    /** 转换检索部门数据结构 */
    normalizerDept(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.fid,
        label: node.label,
        children: node.children
      }
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.dateRange = []
      this.resetForm('queryForm')
      this.handleQuery()
    },
    async handleDelete(item) {
      const res1 = await this.$confirm(`确认删除当前数据项: ${item.projectName}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      item.removeLoading = true
      const res = await deletePrjchk(item.prjchkId).catch(() => false)
      item.removeLoading = false
      if (res === false) return

      this.msgSuccess('删除成功')
      this.list.length > 1 ? this.getList() : this.handleQuery()
    },
    async handleExport() {
      if (!this.list.length) return this.msgInfo('暂无数据')
      const opt = this.getQuery()
      if (!opt) return
      // 不传分页参数
      delete opt.pageNum
      delete opt.pageSize

      const filename = '交付得分表'
      const res1 = await this.$confirm(`确定导出${filename}?`, '警告', { type: 'warning' }).catch(() => false)
      if (res1 !== 'confirm') return

      this.exportLoading = true
      const res = await exportReportPrjchk(opt).catch(() => false)
      this.exportLoading = false
      if (res === false) return

      const elink = document.createElement('a')
      elink.download = `${filename}_${new Date().Format('yyyyMMdd')}.xlsx`
      elink.style.display = 'none'
      elink.href = URL.createObjectURL(new Blob([res]))
      elink.click()
    },
    openDetail(row) {
      const { cfgInfo } = this
      this.$refs.ChkitemScoreDetail.open({ cfgInfo, data: row })
    },
    openProblemInput(row) {
      this.$refs.EvalProblemDialog.open({ data: row })
    }
  }
}
</script>
  <style lang="scss" scoped>
    .tree-select-custom {
      width: 300px;
      /deep/ {
        .vue-treeselect__control {
          height: 28px;
          font-size: 12px;
        }
        .vue-treeselect__placeholder,
        .vue-treeselect__single-value {
          line-height: 26px;
        }
        .vue-treeselect__input-container,
        .vue-treeselect__input {
          height: 26px;
        }
      }
    }
    .default-level {
      color: #909399;
    }
    .green {
      color: #67c23a;
    }
    .blue {
      color: #409eff;
    }
    .red {
      color: #f56c6c;
    }
  </style>
